import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

img1 = cv.imread('/Users/wanggh/Desktop/aa1.png', cv.IMREAD_GRAYSCALE)  # queryImage
img2 = cv.imread('/Users/wanggh/Desktop/a.jpeg', cv.IMREAD_GRAYSCALE)  # trainImage
# img2 = cv.imread('/Users/wanggh/Desktop/original.jpeg', cv.IMREAD_GRAYSCALE)  # trainImage
# 初始化SIFT描述符
sift = cv.SIFT_create()
# 基于SIFT找到关键点和描述符
# img1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)
# img2 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# 默认参数初始化BF匹配器
bf = cv.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)

# 应用比例测试
good = []
for m, n in matches:
    if m.distance < 0.75 * n.distance:
        good.append([m])
# cv.drawMatchesKnn将列表作为匹配项。
img3 = cv.drawMatchesKnn(img1, kp1, img2, kp2, good, None, flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
# plt.imshow(img3), plt.show()
cv.imshow("test", img3)
cv.waitKey(0)
cv.destroyAllWindows()
